package control

import (
	gamemap "FlyFight/Internal/GameMap"
	player "FlyFight/Internal/Player"
	"FlyFight/Internal/game"
	"FlyFight/Internal/room"
	"log"
	"strconv"

	"github.com/gin-gonic/gin"
)



func StartGame(c *gin.Context){
	var sg SetupGame
	if err := c.ShouldBindJSON(&sg); err != nil {
		log.Println(err)
		c.JSON(200, gin.H{
			"code": 200,
			"msg": "error",
		})
		return
	}

	rid,err:=strconv.Atoi(sg.RoomId)
	if err!=nil{
		log.Println("roomid to int err")
		log.Println(err)
		c.JSON(200, gin.H{
			"code": 200,
			"msg": "error",
		})
		return
	}

	if _,ok:=room.RoomList[rid];!ok{
		log.Println("room not exist")
		c.JSON(200, gin.H{
			"code": 200,
			"msg": "error",
		})
	}
	r:=room.RoomList[rid]
	if r==nil{
		log.Println("room is nil")
		c.JSON(200, gin.H{
			"code": 200,
			"msg": "error",
		})
		return
	}

	if !r.CheckExist(uint32(c.GetInt("user_id"))){
		log.Println("user not exist in room")
		c.JSON(200, gin.H{
			"code": 200,
			"msg": "error",
		})
	}

	if !r.CheckUuid(sg.Uuid){
		log.Println("uuid not exist")
		c.JSON(200, gin.H{
			"code": 200,
			"msg": "error",
		})
	}

	g:=game.BuildGame(rid)
	game.Gman.Add(g)
	log.Println("game start success")
}

func GetMap(c *gin.Context){
	b:=gamemap.MapToBinary(gamemap.Ascent)
	c.Header("Content-Type", "application/octet-stream")
	c.Header("X-Data-Format", "uint16-2d-array")
	c.Header("Cache-Control", "public, max-age=3600")
	c.Data(200, "application/octet-stream", b)
}

func GetKill(c *gin.Context){
	uid:=c.GetInt("user_id")
	n:=player.GetKillNum(uid)
	c.JSON(200, gin.H{
		"code": 200,
		"msg": "success",
		"data": n,
	})
}
